<template>
  <!-- 详情 -->
  <el-dialog
    v-el-drag-dialog
    title="选择客户"
    :visible.sync="visible"
    width="70%"
    min-width="1024px"
    append-to-body
    @close="reset"
  >
    <div class="item">
      <el-table-form ref="form">
        <el-form-item class="merge-item">
          <el-select v-model="qType" style="width: 180px; margin-right: 2px;">
            <el-option label="电话" value="csmRgPhone" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <el-option label="客户地址" value="csmRgAddress" />
            <el-option label="备注" value="remark" />
          </el-select>
          <el-input v-model="param" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="客户类型:">
          <el-select v-model="query.csmType" clearable placeholder="请选择">
            <el-option
              v-for="item in csmTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item class="merge-item" label="客户状态:">
          <el-select v-model="query.csmStatus" clearable placeholder="请选择">
            <el-option
              v-for="item in csmStatusMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属机构:">
          <el-tree-select
            v-model="query.orgSNNo"
            :clearable="false"
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: false,
              placeholder: '请选择责任机构',
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>

        <template v-slot:btns>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button type="primary" @click="addPlan">添加</el-button>
        </template>
      </el-table-form>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :immediate-fetch="false"
        :total="tableData.total"
        custom-column
        @row-click="toggleSelection"
        @fetch="fetchData"
      />
    </div>
  </el-dialog>
</template>

<script>
  import { gasCheckPlanClientAssignList, gasCheckPlanClientAssignPlan } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'

  export default {
    name: 'plan-add',
    components: {},
    props: {
      csmTypeMap: {
        type: Array,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        parseTime,
        visible: false,
        planCode: '',
        qType: 'csmRgPhone',
        param: '',
        headerCheckbox: false,
        query: {
          orgSNNo: '',
          csmType: '',
          csmStatus: ''
        },
        // 安检客户明细
        tableData: { // 安检人员明细
          total: 0,
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          {
            prop: 'isCheckbox',
            align: 'center',
            width: 60,
            renderHeader: (h, { row }) => {
              return h('div', [
                h('el-checkbox', {
                  props: {
                    value: this.headerCheckbox
                  },
                  on: {
                    change: this.changeBox
                  }
                })
              ])
            },
            render: (h, { row, $index }) => {
              return h('el-checkbox', {
                props: {
                  value: row.isCheckbox
                },
                on: {
                  change: () => { this.onChangeBox($index) }
                }
              })
            }
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{row.csmType && formatColumnMap(this.csmTypeMap, 'value', row.csmType, 'desc')}</span>
          },
          {
            prop: 'csmRgPhone',
            label: '客户电话'
          },
          {
            prop: 'orgName',
            label: '所属机构'
          },
          {
            prop: 'csmAddress',
            label: '地址'
          },
          {
            prop: 'lastSCheckDt',
            label: '最后安检时间',
            render: (h, { row }) => {
            <span>
              {row.lastSCheckDt && parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}')}
            </span>
            }
          }
        ]
      }
    },
    created() {},
    methods: {
      async open(temp) {
        this.planCode = temp
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.$nextTick(() => {
            this.$refs.lbTable.fetch({ currentPage: 1 })
          })
        })
      },
      toggleSelection(row, column) {
        const index = this.tableData.data.findIndex(v => {
          return v === row
        })
        if (index !== -1) {
          this.onChangeBox(index)
        }
      },
      // 增加
      async addPlan() {
        const flag = this.tableData.data.every(item => item.isCheckbox === false)
        if (flag) {
          this.$message({
            type: 'warning',
            message: '请选中要添加的客户'
          })
          return
        }
        const detailJson = []
        this.tableData.data.filter(item => {
          if (item.isCheckbox === true) {
            detailJson.push(item)
          }
        })
        const { status } = await gasCheckPlanClientAssignPlan({
          detailJson,
          planCode: this.planCode
        })
        console.log('status', status)
        if (status === 200) {
          this.$message({
            type: 'success',
            message: '增加成功'
          })
          this.headerCheckbox = false
          this.$refs.lbTable.fetch({ currentPage: 1 })
          this.$emit('upDataNewlyIncreased')
        }
      },
      // 全选/反选
      changeBox(val) {
        this.headerCheckbox = val
        this.tableData.data = this.tableData.data.map(item => {
          return { ...item, isCheckbox: val }
        })
      },
      onChangeBox(ind) {
        this.tableData.data = this.tableData.data.map((item, index) => {
          if (ind === index) {
            item.isCheckbox = !item.isCheckbox
          }
          return { ...item }
        })
        const flag = this.tableData.data.every(item => item.isCheckbox === true)
        if (flag) {
          this.headerCheckbox = true
        } else {
          this.headerCheckbox = false
        }
      },
      // 查询
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          ...this._getQuery(this.query),
          pageIndex: currentPage,
          pageSize
        }
        if (this.param) {
          params[this.qType] = this.param
        }
        const res = await gasCheckPlanClientAssignList(params)
        this.tableData.data = res.data.rows.map(item => {
          return { ...item, isCheckbox: false }
        })
        console.log('this.tableData.data', this.tableData.data)
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      reset() {
        this.visible = false
        this.planCode = ''
        this.headerCheckbox = false
        this.qType = 'csmRgPhone'
        this.param = ''
        this.query = {
          orgSNNo: '',
          csmType: '',
          csmStatus: ''
        }
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      }
    }
  }
</script>

<style lang="scss" scoped>
.item {
  margin-bottom: 30px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
}
</style>
